// src/main.js
(function () {
    const API_BASE_ORIGIN = 'http://192.168.1.81:8000';

    // AMIS & 依赖（UMD）
    const amis = amisRequire('amis/embed');
    const match = amisRequire('path-to-regexp').match;
    const History = window.History;
    const axios = amisRequire('axios');

    // Hash 路由（纯静态最稳）
    const history = History.createHashHistory();

    const HARD_REFRESH_RE = [/^\/ProfitStatistics(?:$|[?#/])/];
    const HARD_REFRESH_KEY_PREFIX = '__hard_refresh_done__:'; // 存在 sessionStorage 中的“一次性刷新标记”

    function shouldHardRefresh(pathname) {
        return HARD_REFRESH_RE.some(re => re.test(pathname));
    }
    function hasRefreshedOnce(pathname) {
        try { return sessionStorage.getItem(HARD_REFRESH_KEY_PREFIX + pathname) === '1'; } catch (e) { return false; }
    }
    function markRefreshed(pathname) {
        try { sessionStorage.setItem(HARD_REFRESH_KEY_PREFIX + pathname, '1'); } catch (e) { }
    }
    function clearRefreshed(pathname) {
        try { sessionStorage.removeItem(HARD_REFRESH_KEY_PREFIX + pathname); } catch (e) { }
    }

    // 只为 /api 前缀的接口加域名
    function patchUrl(url) {
        if (/^https?:\/\//i.test(url)) return url;
        if (url.startsWith('/api')) return API_BASE_ORIGIN.replace(/\/$/, '') + url;
        return url;
    }

    // AMIS fetcher：统一出入口
    const fetcher = ({ url, method, data, headers, responseType, config }) => {
        const m = (method || 'get').toLowerCase();
        const finalUrl = patchUrl(url);

        const cfg = {
            url: finalUrl,
            method: m,
            headers,
            responseType,
            withCredentials: false, // 若要带 Cookie 改成 true，并配合后端 CORS
            timeout: (config && config.timeout) || 60000,
            ...config
        };

        if (m === 'get' || m === 'delete') cfg.params = data;
        else cfg.data = data; // 支持 JSON / FormData / 上传

        return axios.request(cfg);
    };

    // AMIS 应用
    const app = {
        type: 'app',
        brandName: '量化交易看板',
        logo: '',
        header: {
            type: 'tpl',
            inline: false,
            className: 'w-full',
            tpl: ''
        },
        api: '/pages/site.json'
    };


    // 路由工具
    function normalizeLink(to, location = history.location) {
        to = to || '';
        if (to && to[0] === '#') to = location.pathname + location.search + to;
        else if (to && to[0] === '?') to = location.pathname + to;

        const idx = to.indexOf('?');
        const idx2 = to.indexOf('#');
        let pathname = ~idx ? to.substring(0, idx) : ~idx2 ? to.substring(0, idx2) : to;
        let search = ~idx ? to.substring(idx, ~idx2 ? idx2 : undefined) : '';
        let hash = ~idx2 ? to.substring(idx2) : location.hash;

        if (!pathname) {
            pathname = location.pathname;
        } else if (pathname[0] !== '/' && !/^https?\:\/\//.test(pathname)) {
            let relativeBase = location.pathname;
            const paths = relativeBase.split('/');
            paths.pop();
            let m;
            while ((m = /^\.\.?\//.exec(pathname))) {
                if (m[0] === '../') paths.pop();
                pathname = pathname.substring(m[0].length);
            }
            pathname = paths.concat(pathname).join('/');
        }
        return pathname + search + hash;
    }

    function isCurrentUrl(to, ctx) {
        if (!to) return false;
        const pathname = history.location.pathname;
        const link = normalizeLink(to, { ...location, pathname, hash: '' });
        if (!~link.indexOf('http') && ~link.indexOf(':')) {
            let strict = ctx && ctx.strict;
            return match(link, { decode: decodeURIComponent, strict: typeof strict !== 'undefined' ? strict : true })(pathname);
        }
        return decodeURI(pathname) === link;
    }

    const bootPath = history.location.pathname;
    if (shouldHardRefresh(bootPath) && !hasRefreshedOnce(bootPath)) {
        markRefreshed(bootPath);
        window.location.reload();
        return; // 避免本次继续初始化，等刷新后重来
    }

    // 启动 AMIS
    let amisInstance = amis.embed(
        '#root',
        app,
        {
            location: history.location,
            data: {},
            context: { API_HOST: API_BASE_ORIGIN }, // 需要可在 schema 用 ${API_HOST}
            cache: false
        },
        {
            fetcher, // 关键：所有请求走这里
            updateLocation: (location, replace) => {
                location = normalizeLink(location);
                if (location === 'goBack') return history.goBack();
                else if (
                    (!/^https?\:\/\//.test(location) && location === history.location.pathname + history.location.search) ||
                    location === history.location.href
                ) {
                    return;
                } else if (/^https?\:\/\//.test(location) || !history) {
                    return (window.location.href = location);
                }
                history[replace ? 'replace' : 'push'](location);
            },
            jumpTo: (to, action) => {
                if (to === 'goBack') return history.goBack();
                to = normalizeLink(to);
                if (isCurrentUrl(to)) return;
                if (action && action.actionType === 'url') {
                    action.blank === false ? (window.location.href = to) : window.open(to, '_blank');
                    return;
                } else if (action && action.blank) {
                    window.open(to, '_blank');
                    return;
                }
                if (/^https?:\/\//.test(to)) {
                    window.location.href = to;
                } else if (
                    (!/^https?\:\/\//.test(to) && to === history.pathname + history.location.search) ||
                    to === history.location.href
                ) {
                    // do nothing
                } else {
                    history.push(to);
                }
            },
            isCurrentUrl,
            theme: 'cxd'
        }
    );

    let prevPath = history.location.pathname;

    history.listen(state => {
        const loc = state.location || state;
        const p = loc.pathname;

        // 离开上一个硬刷新页：清标记，保证下次再进入还能再刷新
        if (prevPath && shouldHardRefresh(prevPath) && prevPath !== p) {
            clearRefreshed(prevPath);
        }

        // 进入硬刷新页：若本会话还没刷新过，则标记并刷新一次
        if (shouldHardRefresh(p) && !hasRefreshedOnce(p)) {
            markRefreshed(p);
            window.location.reload();
            return; // 刷新后重启；不再向下 updateProps
        }

        prevPath = p;

        // 常规同步 AMIS 的 location
        amisInstance.updateProps({ location: loc });
    });
})();
